package com.logisticsrepair.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.extra.mail.Mail;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.logisticsrepair.config.ThreadPoolTaskConfig;
import com.logisticsrepair.entity.*;
import com.logisticsrepair.enums.OrderProcessEnum;
import com.logisticsrepair.enums.RepairStatusEnum;
import com.logisticsrepair.service.*;
import com.logisticsrepair.util.RedisUtil;
import com.logisticsrepair.util.mail.MailService;
import com.logisticsrepair.util.responseUtil.ResponseEnum;
import com.logisticsrepair.util.responseUtil.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import java.util.*;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/workerHome")
@Slf4j
public class WorkerHomeController {

    Jedis redis = RedisUtil.getRedis();
    
    private static final String PASSWORD_SALT = "123456"; // 密码加密盐值

    @Autowired
    private RepairOrdersService repairOrdersService;

    @Autowired
    private RepairStatusService repairStatusService;

    @Autowired
    private RepairTypeService repairTypeService;

    @Autowired
    private WorkerService workerService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderProcessService orderProcessService;

    @Autowired
    private MaterialLibraryService materialLibraryService;

    @Autowired
    private ApplyMaterialService applyMaterialService;

    @Autowired
    private ThreadPoolTaskConfig threadPoolTaskConfig;

    @Autowired
    private MailService mailService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @PostMapping("/codeCheck")
    public ResponseUtil workerRegCodeCheck(@RequestBody Map<String, String> code) {
        if (redis.exists(LoginController.ADD_WORKER_PREFIX + code.get("value"))) {
            return ResponseUtil.setE(ResponseEnum.OK).setMsg("受邀成功");
        }
        return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("无效邀请码");
    }

    @GetMapping("/queryNewOrders")
    public ResponseUtil queryNewOrders() {
        return ResponseUtil.setE(ResponseEnum.OK).setData(repairOrdersService.queryNewOrders());
    }

    @PostMapping("/acceptOrder")
    public ResponseUtil acceptOrder(@RequestBody RepairOrdersEntity entity) {
        String workerOpenid = StpUtil.getLoginId().toString();
        entity.setWorkerOpenid(workerOpenid);
        log.info("接单维修工ID: {}", workerOpenid);
        //entity.setUserOpenid(StpUtil.getLoginId().toString());//维修员的openid
        int result = repairOrdersService.acceptOrder(entity.getRepairVersion(),
                entity.getWorkerOpenid(),
                entity.getOrderId());
        switch (result) {
            case 1:
                return ResponseUtil.setE(ResponseEnum.OK).setMsg("接单成功");
            case 0:
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("接单失败");
            case -1:
            default:
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("接单错误");
        }
    }

    @PostMapping("/queryWorkerOrder")
    public ResponseUtil queryWorkerOrder(@RequestBody(required = false) Map<String, Object> condition) {
        if (condition == null) {
            condition = new HashMap<>();
        }
        String workerOpenid = StpUtil.getLoginId().toString();
        condition.put("workerOpenid", workerOpenid);

        List<RepairOrdersEntity> repairOrdersEntities = repairOrdersService.queryWorkerOrder(condition);

        List<Map<String, Object>> orderIdAndStatusCodeList = new ArrayList<>();

        repairOrdersEntities.forEach(item -> {
            HashMap<String, Object> orderIdAndStatusCode = new HashMap<>();
            orderIdAndStatusCode.put("orderId", item.getOrderId());
            Integer statusCodeVal = null;
            if (item.getStatusCode() != null) {
                statusCodeVal = item.getStatusCode().getStatusCode();
            }
            orderIdAndStatusCode.put("statusCode", statusCodeVal == null ? -1 : statusCodeVal);
            orderIdAndStatusCodeList.add(orderIdAndStatusCode);

            /**
             * 脱敏处理
             */
            if (
                    item.getStatusCode() != null && (
                            item.getStatusCode().equals(RepairStatusEnum.REJECTED) ||
                                    item.getStatusCode().equals(RepairStatusEnum.HAVE_FINISHED)
                    )
            ) {
                if (StrUtil.isNotBlank(item.getRepairPhone())) {
                    item.setRepairPhone(DesensitizedUtil.mobilePhone(item.getRepairPhone()));
                }
                if (StrUtil.isNotBlank(item.getRepairAddress())) {
                    item.setRepairAddress(DesensitizedUtil.address(item.getRepairAddress(), item.getRepairAddress().length() / 2));
                }
                if (item.getUserEntity() != null && StrUtil.isNotBlank(item.getUserEntity().getNickname())) {
                    UserEntity userEntity = new UserEntity();
                    userEntity.setNickname(DesensitizedUtil.chineseName(item.getUserEntity().getNickname()));
                    item.setUserEntity(userEntity);
                }
            }
        });
        List<OrderProcessEntity> orderProcessEntities = queryOrderDetailsStep(orderIdAndStatusCodeList);
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("repairOrdersEntities", repairOrdersEntities);
        resultMap.put("orderProcessEntities", orderProcessEntities);
        return ResponseUtil.setE(ResponseEnum.OK).setData(resultMap);
    }

    private List<OrderProcessEntity> queryOrderDetailsStep(List<Map<String, Object>> list) {
        List<OrderProcessEntity> orderHandlerStep = new ArrayList<>();
        List<String> otherOrder = new ArrayList<>();

        //if (map.isEmpty()) return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单信息为不能空");
        for (Map<String, Object> map : list) {
            String order = String.valueOf(map.get("orderId"));
            Object scObj = map.get("statusCode");
            int statusCode = -1;
            if (scObj instanceof Integer) {
                statusCode = (int) scObj;
            } else if (scObj != null) {
                try {
                    statusCode = Integer.parseInt(String.valueOf(scObj));
                } catch (Exception ignore) { }
            }
            /**
             * 只有statusCode为[2待受理, 5待完结]状态的订单，缓存在redis中，其它状态的订单都保存在mysql中
             */
            if (statusCode == RepairStatusEnum.HAVE_ACCEPTED.getStatusCode() ||
                    statusCode == RepairStatusEnum.WAIT_FINISHED.getStatusCode()) {
                try {
                    String res = redis.get(order);
                    if (StrUtil.isEmpty(res)) {
                        OrderProcessEntity orderProcessEntity = new OrderProcessEntity();
                        orderProcessEntity.setOrderId(order);
                        orderProcessEntity.setContactConfirmation(OrderProcessEnum.process.name());

                        redis.setnx(order, JSON.toJSONString(orderProcessEntity));
                        orderHandlerStep.add(orderProcessEntity);
                    } else {
                        orderHandlerStep.add(JSONObject.parseObject(res, OrderProcessEntity.class));
                    }
                } catch (Exception e) {
                    // 当Redis不可用或发生异常时，回退为默认进度对象，避免接口报500
                    OrderProcessEntity orderProcessEntity = new OrderProcessEntity();
                    orderProcessEntity.setOrderId(order);
                    orderProcessEntity.setContactConfirmation(OrderProcessEnum.process.name());
                    orderHandlerStep.add(orderProcessEntity);
                }
                continue;
            }
            /**
             * 其它状态的订单
             */
            otherOrder.add(order);
        }

        if (!otherOrder.isEmpty()) {
            List<OrderProcessEntity> entityList = orderProcessService.listByIds(otherOrder);
            orderHandlerStep.addAll(entityList);
        }

        return orderHandlerStep;
    }

    @PostMapping("/confirmContact")
    public ResponseUtil confirmContact(@RequestBody Map<String, Object> map) {
        String order = map.get("order").toString();
        if (map.isEmpty()) return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单信息不能为空");

        OrderProcessEntity byId = orderProcessService.getById(order);
        if (byId != null) return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单信息有误");

        OrderProcessEntity orderProcessEntity = new OrderProcessEntity();
        orderProcessEntity.setOrderId(order);
        orderProcessEntity.setContactConfirmation(OrderProcessEnum.success.name());
        orderProcessEntity.setApplyMaterial(OrderProcessEnum.process.name());

        redis.set(order, JSON.toJSONString(orderProcessEntity));
        return ResponseUtil.setE(ResponseEnum.OK).setData(orderProcessEntity).setMsg("联系确认成功");
    }


    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/rejectOrder")
    public ResponseUtil rejectOrder(@RequestBody RepairOrdersEntity repairOrdersEntity) {
        if (!repairOrdersService.rejectOrder(repairOrdersEntity))
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单驳回失败1");

        OrderProcessEntity orderProcessEntity = new OrderProcessEntity();
        orderProcessEntity.setOrderId(repairOrdersEntity.getOrderId());
        orderProcessEntity.setContactConfirmation(OrderProcessEnum.error.name());

        boolean save = orderProcessService.save(orderProcessEntity);
        if (!save) return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单驳回失败2");
        redis.del(repairOrdersEntity.getOrderId());
        return ResponseUtil.setE(ResponseEnum.OK).setData(orderProcessEntity).setMsg("订单驳回成功");
    }

    @GetMapping("/getMaterialLibrary")
    public ResponseUtil getMaterialLibrary() {
        List<MaterialLibraryEntity> list = materialLibraryService.list();
        int size = list.size();
        for (int i = 0; i < size; i++) {
            if (list.get(i).getMaterialAmount().intValue() <= 0){
                list.remove(i);
                i--;
                size--;
            }
        }
        return ResponseUtil.setE(ResponseEnum.OK).setData(list);
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/submitApply")
    public ResponseUtil submitApply(@RequestBody Map<String, Object> map) {
        List<MaterialLibraryEntity> applyData = JSONArray.parseArray(map.get("applyData").toString(), MaterialLibraryEntity.class);

        String hashCode = map.get("hashCode").toString();

        String md5Hex = DigestUtil.md5Hex(map.get("applyData").toString());

        String orderId = map.get("orderId").toString();

        if (!md5Hex.equals(hashCode) || applyData.isEmpty())
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单信息有误");

        LambdaQueryWrapper<ApplyMaterialEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApplyMaterialEntity::getOrderId, orderId);
        List<ApplyMaterialEntity> list = applyMaterialService.list(lambdaQueryWrapper);

        if (!list.isEmpty()) return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单信息有误");
        /**
         * 1、减库存
         */
        for (MaterialLibraryEntity entity : applyData) {
            MaterialLibraryEntity materialLibraryEntity = (MaterialLibraryEntity) entity.clone();
            materialLibraryEntity.setMaterialName(null);
            materialLibraryEntity.setMaterialPrice(null);
            materialLibraryEntity.setMaterialAmount(materialLibraryEntity.getMaterialAmount() - materialLibraryEntity.getTakeAmount());
            boolean updateRes = materialLibraryService.updateById(materialLibraryEntity);
            if (!updateRes) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("申请材料失败，请重试。");
            }
        }

        /**
         * 2、存订单
         */
        DateTime applyTime = DateUtil.date();
        ArrayList<ApplyMaterialEntity> applyMaterialEntities = new ArrayList<>();
        for (MaterialLibraryEntity entity : applyData) {
            ApplyMaterialEntity applyMaterialEntity = new ApplyMaterialEntity();
            applyMaterialEntity.setOrderId(orderId);
            applyMaterialEntity.setMaterialId(entity.getMaterialId());
            applyMaterialEntity.setMaterialPrice(entity.getMaterialPrice());
            applyMaterialEntity.setTakeAmount(entity.getTakeAmount());
            applyMaterialEntity.setApplyTime(applyTime);
            applyMaterialEntity.setApplyStatus(true);  // 修复：自动批准材料申请
            applyMaterialEntity.setChargeOn(false);    // 初始状态：收费开关关闭
            applyMaterialEntity.setChargeStatus(false); // 初始状态：未缴费
            applyMaterialEntities.add(applyMaterialEntity);
        }
        applyMaterialService.saveBatch(applyMaterialEntities);

        /**
         * 3、更新步骤
         */
        OrderProcessEntity orderProcessEntity = new OrderProcessEntity();
        orderProcessEntity.setOrderId(orderId);
        orderProcessEntity.setContactConfirmation(OrderProcessEnum.success.name());
        orderProcessEntity.setApplyMaterial(OrderProcessEnum.success.name());
        orderProcessEntity.setChargeOn(OrderProcessEnum.process.name());

        redis.set(orderId, JSON.toJSONString(orderProcessEntity));

        ThreadPoolExecutor threadPoolExecutor = threadPoolTaskConfig.threadPoolExecutor();
        threadPoolExecutor.execute(() -> {
            WorkerEntity workerEntity = workerService.queryWorkerEmailInRepairOrdersByWorkerOpenid(orderId);
            String voucher = RandomUtil.randomNumbers(6);
            HashMap<String, Object> data = new HashMap<>();
            data.put("orderId", orderId);
            data.put("applyTime", applyTime);
            data.put("voucher", voucher);
            data.put("workerName", workerEntity.getWorkerName());
            redis.set("voucher:" + voucher, JSON.toJSONString(data));
            mailService.sendHtmlTemplateMail(workerEntity.getWorkerEmail(), "材料申报凭证", data, "EmailTemplate");
        });

        return ResponseUtil.setE(ResponseEnum.OK).setMsg("材料申报成功").setData(orderProcessEntity);
    }

    @PostMapping("/noApply")
    public ResponseUtil noApply(@RequestBody Map<String, Object> map) {
        // 先检查map是否为空
        if (map == null || map.isEmpty() || !map.containsKey("order")) {
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单信息不能为空");
        }

        // 安全地获取order值
        Object orderObj = map.get("order");
        if (orderObj == null) {
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单ID不能为空");
        }

        String order = orderObj.toString();
        if (order.trim().isEmpty()) {
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单ID不能为空");
        }

        // 获取当前登录的维修工ID
        String workerOpenid = StpUtil.getLoginId().toString();
        
        // 检查订单是否存在且属于当前维修工
        LambdaQueryWrapper<RepairOrdersEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RepairOrdersEntity::getOrderId, order)
                   .eq(RepairOrdersEntity::getWorkerOpenid, workerOpenid);
        
        RepairOrdersEntity orderEntity = repairOrdersService.getOne(queryWrapper);
        if (orderEntity == null) {
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单信息有误");
        }

        // 检查是否已经申报过材料，如果有则将其状态设为无效
        LambdaQueryWrapper<ApplyMaterialEntity> applyQueryWrapper = new LambdaQueryWrapper<>();
        applyQueryWrapper.eq(ApplyMaterialEntity::getOrderId, order);
        List<ApplyMaterialEntity> existingMaterials = applyMaterialService.list(applyQueryWrapper);
        
        String resultMessage = "设置无需申报成功，收费项自动关闭";
        if (!existingMaterials.isEmpty()) {
            // 如果有已申报的材料，将其状态设为无效（未完成状态）
            for (ApplyMaterialEntity material : existingMaterials) {
                material.setApplyStatus(false); // 设为未完成状态
                material.setChargeOn(false);    // 关闭收费
                material.setChargeStatus(false); // 设为未收费
                material.setChargeTime(null);   // 清空收费时间
            }
            boolean materialsUpdated = applyMaterialService.updateBatchById(existingMaterials);
            if (!materialsUpdated) {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("更新材料申报状态失败");
            }
            resultMessage = "已取消原有材料申报，设置为无需申报，收费项自动关闭";
        }

        // 更新订单状态
        OrderProcessEntity orderProcessEntity = new OrderProcessEntity();
        orderProcessEntity.setOrderId(order);
        orderProcessEntity.setContactConfirmation(OrderProcessEnum.success.name());
        orderProcessEntity.setApplyMaterial(OrderProcessEnum.error.name());
        orderProcessEntity.setChargeOn(OrderProcessEnum.error.name());
        orderProcessEntity.setOrderCompleted(OrderProcessEnum.process.name());

        // 更新Redis缓存并设置订单状态
        try {
            redis.set(order, JSON.toJSONString(orderProcessEntity));
            
            // 更新订单状态为待完结
            RepairOrdersEntity updateEntity = new RepairOrdersEntity();
            updateEntity.setOrderId(order);
            updateEntity.setStatusCode(RepairStatusEnum.WAIT_FINISHED);
            boolean updated = repairOrdersService.updateById(updateEntity);
            
            if (!updated) {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("更新订单状态失败");
            }
            
            return ResponseUtil.setE(ResponseEnum.OK).setData(orderProcessEntity).setMsg(resultMessage);
        } catch (Exception e) {
            log.error("noApply处理失败: {}", e.getMessage(), e);
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("系统处理失败，请重试");
        }
    }

    @PostMapping("/getOrderMaterialInfo")
    public ResponseUtil getOrderMaterialInfo(@RequestBody Map<String, Object> map) {
        String orderId = map.get("orderId").toString();
        List<ApplyMaterialEntity> applyMaterialEntities = applyMaterialService.queryOrderMaterialInfo(orderId);
        return ResponseUtil.setE(ResponseEnum.OK).setData(applyMaterialEntities).setMsg("材料订单查询成功");
    }

    @Transactional
    @PostMapping("/submitChargeItem")
    public ResponseUtil submitChargeItem(@RequestBody List<ApplyMaterialEntity> list) {
        if (list.isEmpty()) return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单信息错误");

        // 检查材料申请记录是否存在
        String orderId = list.get(0).getOrderId();
        LambdaQueryWrapper<ApplyMaterialEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApplyMaterialEntity::getOrderId, orderId);
        List<ApplyMaterialEntity> existingMaterials = applyMaterialService.list(queryWrapper);
        
        if (existingMaterials.isEmpty()) {
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("请先申请材料后再提交收费项！");
        }
        
        // 验证前端传来的applyId是否都存在
        Set<String> existingApplyIds = existingMaterials.stream()
                .map(ApplyMaterialEntity::getApplyId)
                .collect(Collectors.toSet());
        
        for (ApplyMaterialEntity item : list) {
            if (!existingApplyIds.contains(item.getApplyId())) {
                return ResponseUtil.setE(ResponseEnum.FAIL)
                        .setMsg("材料申请记录不存在，请刷新后重试！applyId: " + item.getApplyId());
            }
        }

        ArrayList<ApplyMaterialEntity> entities = new ArrayList<>();
        for (ApplyMaterialEntity applyMaterialEntity : list) {
            ApplyMaterialEntity entity = new ApplyMaterialEntity();
            entity.setApplyId(applyMaterialEntity.getApplyId());
            entity.setChargeOn(true);
            entity.setApplyStatus(true);  // 自动批准材料申请
            entities.add(entity);
        }
        boolean batchById = applyMaterialService.updateBatchById(entities);
        if (!batchById) return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("收费项开启失败");

        String openid = StpUtil.getLoginId().toString();

        LambdaUpdateWrapper<RepairOrdersEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(RepairOrdersEntity::getOrderId, orderId)
                .eq(RepairOrdersEntity::getWorkerOpenid, openid)
                .set(RepairOrdersEntity::getStatusCode, RepairStatusEnum.WAIT_PAY);

        repairOrdersService.update(lambdaUpdateWrapper);

        OrderProcessEntity orderProcessEntity = new OrderProcessEntity();
        orderProcessEntity.setOrderId(list.get(0).getOrderId());
        orderProcessEntity.setContactConfirmation(OrderProcessEnum.success.name());
        orderProcessEntity.setApplyMaterial(OrderProcessEnum.success.name());
        orderProcessEntity.setChargeOn(OrderProcessEnum.success.name());
        orderProcessEntity.setOrderCompleted(OrderProcessEnum.process.name());
        redis.set(list.get(0).getOrderId(), JSON.toJSONString(orderProcessEntity));

        return ResponseUtil.setE(ResponseEnum.OK).setMsg("收费项开启成功").setData(orderProcessEntity);
    }

    @GetMapping("/noChargeItem")
    public ResponseUtil noChargeItem(@RequestParam String orderId) {
        if (StrUtil.isEmpty(orderId)) return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单信息错误");
        OrderProcessEntity orderProcessEntity = new OrderProcessEntity();
        orderProcessEntity.setOrderId(orderId);
        orderProcessEntity.setContactConfirmation(OrderProcessEnum.success.name());
        orderProcessEntity.setApplyMaterial(OrderProcessEnum.success.name());
        orderProcessEntity.setChargeOn(OrderProcessEnum.error.name());
        orderProcessEntity.setOrderCompleted(OrderProcessEnum.process.name());
        redis.set(orderId, JSON.toJSONString(orderProcessEntity));
        return ResponseUtil.setE(ResponseEnum.OK).setMsg("无需收费").setData(orderProcessEntity);
    }

    @GetMapping("/queryOrderCompletedInfo")
    public ResponseUtil queryOrderCompletedInfo(@RequestParam String orderId) {
        if (StrUtil.isEmpty(orderId)) return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单信息错误");
        List<ApplyMaterialEntity> list = applyMaterialService.queryOrderMaterialInfo(orderId);
        return ResponseUtil.setE(ResponseEnum.OK).setData(list);
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/completedOrderIsNotApplyMaterial")
    public ResponseUtil completedOrderIsNotApplyMaterial(@RequestBody Map<String, Object> requestData){
        try {
            if (requestData == null || requestData.isEmpty() || !requestData.containsKey("orderId")) {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单信息不能为空");
            }

            String orderId = requestData.get("orderId").toString();
            if (StrUtil.isEmpty(orderId)) {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单ID不能为空");
            }
            log.info("开始完结订单: {}", orderId);

            // 更新订单状态
            RepairOrdersEntity repairOrdersEntity = new RepairOrdersEntity();
            repairOrdersEntity.setOrderId(orderId);
            repairOrdersEntity.setStatusCode(RepairStatusEnum.HAVE_FINISHED);
            repairOrdersEntity.setRepairComplateDate(new Date());
            boolean orderUpdated = repairOrdersService.updateById(repairOrdersEntity);
            
            if (!orderUpdated) {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("更新订单状态失败");
            }

            // 处理订单流程状态
            OrderProcessEntity orderProcessEntity;
            String redisData = redis.get(orderId);
            
            if (StrUtil.isNotEmpty(redisData)) {
                // Redis中有数据，解析并更新
                try {
                    orderProcessEntity = JSONObject.parseObject(redisData, OrderProcessEntity.class);
                    if (orderProcessEntity == null) {
                        throw new RuntimeException("Redis数据解析为null");
                    }
                    orderProcessEntity.setOrderCompleted(OrderProcessEnum.success.name());
                    log.info("从Redis获取并更新订单流程状态: {}", orderId);
                } catch (Exception e) {
                    log.error("解析Redis数据失败，创建新的订单流程状态: {}", e.getMessage());
                    // 如果解析失败，创建新的订单流程状态
                    orderProcessEntity = createOrderProcessEntity(orderId);
                }
            } else {
                log.warn("Redis中未找到订单流程数据，创建新的订单流程状态: {}", orderId);
                // Redis中没有数据，创建新的订单流程状态
                orderProcessEntity = createOrderProcessEntity(orderId);
            }

            // 保存或更新订单流程状态到数据库
            boolean processUpdated = orderProcessService.saveOrUpdate(orderProcessEntity);
            if (!processUpdated) {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("更新订单流程状态失败");
            }

            // 清理Redis缓存
            redis.del(orderId);
            log.info("订单完结成功: {}", orderId);

            // 确保返回的数据不为null
            if (orderProcessEntity == null) {
                log.error("orderProcessEntity为null，创建默认数据");
                orderProcessEntity = createOrderProcessEntity(orderId);
            }

            return ResponseUtil.setE(ResponseEnum.OK).setMsg("订单已完结").setData(orderProcessEntity);
            
        } catch (Exception e) {
            log.error("完结订单失败: {}", e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("系统处理失败，请重试");
        }
    }

    /**
     * 创建新的订单流程状态实体
     */
    private OrderProcessEntity createOrderProcessEntity(String orderId) {
        OrderProcessEntity orderProcessEntity = new OrderProcessEntity();
        orderProcessEntity.setOrderId(orderId);
        orderProcessEntity.setContactConfirmation(OrderProcessEnum.success.name());
        orderProcessEntity.setApplyMaterial(OrderProcessEnum.error.name());
        orderProcessEntity.setChargeOn(OrderProcessEnum.error.name());
        orderProcessEntity.setOrderCompleted(OrderProcessEnum.success.name());
        return orderProcessEntity;
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/completedOrder")
    public ResponseUtil completedOrder(@RequestBody List<ApplyMaterialEntity> applyMaterialEntities) {
        if (applyMaterialEntities.isEmpty())  return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("订单信息不能为空");

        /**
         * 完结材料申报订单信息
         */
            ArrayList<ApplyMaterialEntity> entityArrayList = new ArrayList<>();
            for (ApplyMaterialEntity entity : applyMaterialEntities) {
                ApplyMaterialEntity applyMaterialEntity = new ApplyMaterialEntity();
                applyMaterialEntity.setApplyId(entity.getApplyId());
                if (!entity.getChargeOn()) applyMaterialEntity.setChargeTime(new Date());
                applyMaterialEntity.setApplyStatus(true);
                entityArrayList.add(applyMaterialEntity);
            }
            applyMaterialService.updateBatchById(entityArrayList);


        /**
         * 完结申报订单信息
         */
        String orderId = applyMaterialEntities.get(0).getOrderId();
        LambdaUpdateWrapper<RepairOrdersEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(RepairOrdersEntity::getOrderId, orderId)
                .eq(RepairOrdersEntity::getWorkerOpenid, StpUtil.getLoginId().toString())
                .set(RepairOrdersEntity::getStatusCode, RepairStatusEnum.HAVE_FINISHED)
                .set(RepairOrdersEntity::getRepairComplateDate, DateUtil.date());
        repairOrdersService.update(lambdaUpdateWrapper);


        /**
         * 录入订单状态处理信息
         */
        OrderProcessEntity orderProcessEntity;
        String redisData = redis.get(orderId);
        
        if (StrUtil.isNotEmpty(redisData)) {
            try {
                orderProcessEntity = JSONObject.parseObject(redisData, OrderProcessEntity.class);
                if (orderProcessEntity == null) {
                    throw new RuntimeException("Redis数据解析为null");
                }
                log.info("从Redis获取订单流程状态: {}", orderId);
            } catch (Exception e) {
                log.error("解析Redis数据失败，创建新的订单流程状态: {}", e.getMessage());
                orderProcessEntity = createOrderProcessEntity(orderId);
            }
        } else {
            log.warn("Redis中未找到订单流程数据，创建新的订单流程状态: {}", orderId);
            orderProcessEntity = createOrderProcessEntity(orderId);
        }
        
        orderProcessEntity.setOrderCompleted(OrderProcessEnum.success.name());
        orderProcessService.saveOrUpdate(orderProcessEntity);
        redis.del(orderId);

        // 确保返回的数据不为null
        if (orderProcessEntity == null) {
            log.error("orderProcessEntity为null，创建默认数据");
            orderProcessEntity = createOrderProcessEntity(orderId);
            orderProcessEntity.setOrderCompleted(OrderProcessEnum.success.name());
        }

        return ResponseUtil.setE(ResponseEnum.OK).setMsg("订单已完结").setData(orderProcessEntity);
    }

    /**
     * 修改维修工密码
     */
    @SaCheckLogin
    @PostMapping("/updatePassword")
    public ResponseUtil updatePassword(@RequestBody Map<String, String> params) {
        try {
            String oldPassword = params.get("oldPassword");
            String newPassword = params.get("newPassword");
            
            // 参数验证
            if (oldPassword == null || newPassword == null) {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("参数不能为空");
            }
            
            if (newPassword.length() < 6) {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("新密码长度不能少于6位");
            }
            
            // 获取当前登录维修工ID
            String workerId = StpUtil.getLoginId().toString();
            
            // 查询维修工信息
            WorkerEntity worker = workerService.getById(workerId);
            if (worker == null) {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("维修工不存在");
            }
            
            // 验证原密码
            String encryptedOldPassword = DigestUtil.md5Hex(oldPassword + PASSWORD_SALT);
            if (!encryptedOldPassword.equals(worker.getPassword())) {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("原密码错误");
            }
            
            // 检查新密码是否与原密码相同
            String encryptedNewPassword = DigestUtil.md5Hex(newPassword + PASSWORD_SALT);
            if (encryptedNewPassword.equals(worker.getPassword())) {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("新密码不能与原密码相同");
            }
            
            // 更新密码
            worker.setPassword(encryptedNewPassword);
            boolean success = workerService.updateById(worker);
            
            if (success) {
                return ResponseUtil.setE(ResponseEnum.OK).setMsg("密码修改成功");
            } else {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("密码修改失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("系统错误：" + e.getMessage());
        }
    }
}
